package org.stjs.generator;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class STJSTranspiler {

	public static void main(String[] args) {
		STJSTranspiler.transpileClass("src",
				"org.stjs.generator.STJSTranspiler", null);
	}

	public static void transpileClass(String sourceFolderPath,
			String className, URLClassLoader classLoader) {

		Generator gen = new Generator();

		try {
			File f = new File(sourceFolderPath);
			File p = new File(f.getParentFile(), "js-" + f.getName());
			generateJs(gen, className, sourceFolderPath, p.getPath(),
					classLoader);
		} catch (MalformedURLException e) {
			// FIXME Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// FIXME Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void generateJs(Generator gen, final String className,
			String sourceFolderPath, String targetFolderPath,
			ClassLoader builtProjectClassLoader) throws MalformedURLException,
			ClassNotFoundException {
		final String path = sourceFolderPath;

		List<File> dependencies = new ArrayList<File>();
		String outputDir = targetFolderPath;

		List<URL> classpathElements = new ArrayList<URL>();
		classpathElements.add(new File(path).toURI().toURL());
		for (File dep : dependencies) {
			classpathElements.add(dep.toURI().toURL());
		}

		File sourceFolder = new File(path);
		GenerationDirectory targetFolder = new GenerationDirectory(new File(
				outputDir), null, null);
		File generationFolder = targetFolder.getAbsolutePath();

		GeneratorConfigurationBuilder configBuilder = new GeneratorConfigurationBuilder();
		Package p = builtProjectClassLoader.loadClass(className).getPackage();
		String packageName = p == null ? "" : p.getName();
		configBuilder.allowedPackage(packageName);
		GeneratorConfiguration configuration = configBuilder.build();

		gen.init(builtProjectClassLoader, configuration.getSourceEncoding());
		gen.generateJavascript(builtProjectClassLoader, className,
				sourceFolder, targetFolder, generationFolder, configuration);
	}
}
